<?php

namespace app\bsadmin\controller;

use app\common\model\VipRuleValue;
use think\facade\View;
use think\facade\Cache;
use think\facade\Session;
use think\facade\Db;
use think\helper\Str;
use helper\Time;
use helper\Baidu;
use think\facade\Validate;
use app\common\validate\User as UserValidate;
use app\common\validate\UserName as UserNameValidate;
use app\common\validate\Company as CompanyValidate;
use app\common\validate\CompanyContent as CompanyContentValidate;
use think\exception\ValidateException;
use app\common\model\User as UserModel;
use app\common\model\UserInfo as UserInfoModel;
use app\common\model\UserTimer as UserTimerModel;
use app\common\model\UserVip as UserVipModel;
use app\common\model\UserScore as UserScoreModel;
use app\common\model\Vip as VipModel;
use app\common\model\VipRule as VipRuleModel;
use app\common\model\UserVipRule as UserVipRuleModel;
use app\common\model\Jobs as JobsModel;
use app\common\model\Company as CompanyModel;
use app\common\model\CompanyContent as CompanyContentModel;
use app\common\model\StatusAlias as StatusAliasModel;
use app\common\model\CompanyIndustry as CompanyIndustryModel;
use app\common\model\CompanyDemeanor as CompanyDemeanorModel;
use app\common\model\CompanyAttestation as CompanyAttestationModel;
use app\bsadmin\model\Config as ConfigModel;
use app\bsadmin\model\Admin as AdminModel;
use app\common\controller\Vip as VipController;
use app\common\model\CompanyLogoExamine as CompanyLogoExamineModel;
use app\common\model\CrmCustomer as CrmCustomerModel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;

class Company extends Base
{
    public function index()
    {
        if (request()->isAjax()) {
            $G = request()->get();
            //            if (!empty($G['advanceSearch']))
            //                $where = $this->getSearchCompanyWhere();
            //            else
            $where = $this->getSearchCompanyWhere();
            $Data = CompanyModel::alias('company')->where($where)
                ->join('user user', 'user.id = company.uid')
                ->join('user_info user_info', 'user_info.uid = company.uid', 'LEFT')
                ->join('user_vip user_vip', 'user_vip.uid = company.uid', 'LEFT')
                ->join('vip vip', 'vip.level = user_vip.company_vip_level AND vip.is_company=1 AND vip.status=1', 'LEFT')
                ->join('company_content content', 'content.cid = company.id')
                ->join('api_app app', 'app.app_id = company.app_id', 'LEFT')
                ->field('company.*,user.mobile,user_info.nickname,user_info.headimg,vip.title as vip_title,vip.id as vid,user_vip.company_vip_time,app.app_name')
                ->order('id desc')->paginate($G['pageSize'])->each(function ($v) {
                    $v['nickname'] = $v['nickname'] ? base64_decode($v['nickname']) : '';
                    $v['headimg'] = $v['headimg'] ? config('web.imgurl') . $v['headimg'] : '';
                    $v['app_name'] = $v['app_name'] ? $v['app_name'] : '后台添加';
                    $v['refresh_time'] = $v['refresh_time'] ? date('Y-m-d H:i', $v['refresh_time']) : '';
                    $v['company_vip_time'] = $v['company_vip_time'] && $v['company_vip_time'] > time() ? date('Y-m-d', $v['company_vip_time']) : '';
                    $v['jobs_count'] = JobsModel::where(['company_id' => $v->id])->count();
                    $v['company_info'] = 0;
                    $v['data'] = [];
                    return $v;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('', 0, $Data);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        } else {
            $AdminModelObj = AdminModel::where(['status' => 1]);
            if (config('xy_crm.admin_role_id'))
                $AdminModelObj->whereIn('role_id', config('xy_crm.admin_role_id'));
            $AdminModel = $AdminModelObj->field('id,headimg,nickname,adviser_default')->select();
            View::assign('admin', $AdminModel);
            $attestation = StatusAliasModel::getCate('company/attestation');
            View::assign('attestation', $attestation);
            $nature = StatusAliasModel::getCate('company/nature');
            View::assign('nature', $nature);
            $finance = StatusAliasModel::getCate('company/finance');
            View::assign('finance', $finance);
            $size_type = StatusAliasModel::getCate('company/size_type');
            View::assign('size_type', $size_type);
            $corporate_welfare = StatusAliasModel::getCate('company/corporate_welfare');
            View::assign('corporate_welfare', $corporate_welfare);
            $industry = CompanyIndustryModel::getCate();
            View::assign('industry', $industry);
            $VipController = VipController::getCate();
            View::assign('vip', $VipController);
            $vipRule = VipRuleModel::select();
            View::assign('vipRule', $vipRule);
            $vipRuleValue = VipRuleValue::select();
            View::assign('vipRuleValue', $vipRuleValue);

            if (request()->isMobile())
                return View::fetch('index_mobile');
            return View::fetch();
        }
    }

    /**
     * 高级搜索
     * hhm
     * @return void
     */
    public function advancedSearch()
    {
        $S = input();
        $where = [];
        if (!empty($S['searchData'])) {
            foreach ($S['searchData'] as $v) {
                switch ($v['value']) {
                    case 'FamousEnterprises': //是否名企
                        //-1代表全部
                        if ($v['index'] != -1)
                            $where[] = ['company.is_famous', '=', $v['index']];
                        break;
                    case 'EnterpriseCertification': //企业认证
                        if ($v['index'] != -1)
                            $where[] = ['company.attestation', '=', $v['index']];
                        break;
                    case 'EnterprisePackage': //企业套餐
                        if ($v['index'] != -1)
                            $where[] = ['user_vip.company_vip_level', '=', $v['index']];
                        break;
                    case 'VipExpirationTime': //到期时间
                        if ($v['index'] != -1)
                            $where[] = ['user_vip.company_vip_time', '<=', getPastTimes($v['index'])];
                        $where[] = ['user_vip.company_vip_time', '>=', getPastTimes(0)];
                        break;
                    case 'RecentLogin': //最近登录时间
                        if ($v['index'] != -1)
                            $where[] = ['timer.login_time', '>=', getPastTimes($v['index'])];
                        break;
                    case 'RecentlyRegistered': //最近注册时间
                        if ($v['index'] != -1)
                            $where[] = ['timer.register_time', '>=', getPastTimes($v['index'])];
                        break;
                    case 'source': //数据来源
                        if ($v['index'] != -1)
                            $where[] = ['app.app_id', '=', $v['index']];
                        break;
                }
            }
        }
        $Data = CompanyModel::alias('company')->where($where)
            ->join('user user', 'user.id = company.uid')
            ->join('user_info user_info', 'user_info.uid = company.uid', 'LEFT')
            ->join('user_vip user_vip', 'user_vip.uid = company.uid', 'LEFT')
            ->join('vip vip', 'vip.level = user_vip.company_vip_level AND vip.is_company=1 AND vip.status=1', 'LEFT')
            ->join('company_content content', 'content.cid = company.id')
            ->join('api_app app', 'app.app_id = company.app_id', 'LEFT')
            ->join('user_timer timer', 'timer.uid = company.uid', 'LEFT')
            ->field('company.*,user.mobile,user_info.nickname,user_info.headimg,vip.title as vip_title,user_vip.company_vip_time,app.app_name')
            ->order('id desc')->paginate($S['pageSize'])->each(function ($v) {
                $v['nickname'] = $v['nickname'] ? base64_decode($v['nickname']) : '';
                $v['headimg'] = $v['headimg'] ? config('web.imgurl') . $v['headimg'] : '';
                $v['app_name'] = $v['app_name'] ? $v['app_name'] : '后台添加';
                $v['refresh_time'] = $v['refresh_time'] ? date('Y-m-d H:i', $v['refresh_time']) : '';
                $v['company_vip_time'] = $v['company_vip_time'] && $v['company_vip_time'] > time() ? date('Y-m-d', $v['company_vip_time']) : '';
                $v['jobs_count'] = JobsModel::where(['company_id' => $v->id])->count();
                $v['company_info'] = 0;
                $v['data'] = [];
                return $v;
            });
        if ($Data->items()) {
            return $this->ajaxReturn('', 0, $Data);
        } else {
            return $this->ajaxReturn('暂无数据~', -100);
        }
    }

    public function recycleBin()
    {
        if (request()->isAjax()) {
            $G = request()->get();
            $where = $this->getSearchCompanyWhere();
            $Data = CompanyModel::onlyTrashed()->alias('company')->where($where)
                ->join('user user', 'user.id = company.uid')
                ->join('user_info user_info', 'user_info.uid = company.uid', 'LEFT')
                ->join('user_vip user_vip', 'user_vip.uid = company.uid', 'LEFT')
                ->join('vip vip', 'vip.level = user_vip.company_vip_level AND vip.is_company=1 AND vip.status=1', 'LEFT')
                ->join('company_content content', 'content.cid = company.id')
                ->join('api_app app', 'app.app_id = company.app_id', 'LEFT')
                ->field('company.*,user.mobile,user_info.nickname,user_info.headimg,vip.title as vip_title,user_vip.company_vip_time,app.app_name')
                ->order('company.delete_time desc')->paginate($G['pageSize'])->each(function ($v) {
                    $v['nickname'] = $v['nickname'] ? base64_decode($v['nickname']) : '';
                    $v['headimg'] = $v['headimg'] ? config('web.imgurl') . $v['headimg'] : '';
                    $v['app_name'] = $v['app_name'] ? $v['app_name'] : '后台添加';
                    $v['refresh_time'] = $v['refresh_time'] ? date('Y-m-d H:i', $v['refresh_time']) : '';
                    $v['company_vip_time'] = $v['company_vip_time'] && $v['company_vip_time'] > time() ? date('Y-m-d', $v['company_vip_time']) : '';
                    $v['jobs_count'] = JobsModel::where(['company_id' => $v->id])->count();
                    $v['company_info'] = 0;
                    $v['data'] = [];
                    return $v;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('', 0, $Data);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        } else {
            $AdminModelObj = AdminModel::where(['status' => 1]);
            if (config('xy_crm.admin_role_id'))
                $AdminModelObj->whereIn('role_id', config('xy_crm.admin_role_id'));
            $AdminModel = $AdminModelObj->field('id,headimg,nickname,adviser_default')->select();
            View::assign('admin', $AdminModel);
            $attestation = StatusAliasModel::getCate('company/attestation');
            View::assign('attestation', $attestation);
            $nature = StatusAliasModel::getCate('company/nature');
            View::assign('nature', $nature);
            $finance = StatusAliasModel::getCate('company/finance');
            View::assign('finance', $finance);
            $size_type = StatusAliasModel::getCate('company/size_type');
            View::assign('size_type', $size_type);
            $corporate_welfare = StatusAliasModel::getCate('company/corporate_welfare');
            View::assign('corporate_welfare', $corporate_welfare);
            $industry = CompanyIndustryModel::getCate();
            View::assign('industry', $industry);
            $VipController = VipController::getCate();
            View::assign('vip', $VipController);
            return View::fetch();
        }
    }
    public function getSearchCompanyWhere()
    {
        //        $G = request()->get();
        $G = input();
        $where = [];
        if ($G['key']) {
            switch ($G['search_type']) {
                case 'id':
                    $where[] = ['company.id', '=', $G['key']];
                    break;
                case 'uid':
                    $where[] = ['user.id', '=', $G['key']];
                    break;
                case 'uscc':
                    $where[] = ['company.uscc', '=', $G['key']];
                    break;
                case 'company_name':
                    $where[] = ['company.title', 'like', '%' . $G['key'] . '%'];
                    break;
                case 'contacts_mobile':
                    $where[] = ['content.contacts_mobile', '=', $G['key']];
                    break;
                case 'contacts_email':
                    $where[] = ['content.contacts_email', '=', $G['key']];
                    break;
            }
        }
        if ($G['attestation'] != 'all') {
            $where[] = ['company.attestation', '=', $G['attestation']];
        }
        if (!empty($G['adviser_id'])) {
            $where[] = ['company.adviser_id', '=', $G['adviser_id']];
        }
        if (isset($G['vip_level']) && $G['vip_level'] != 'all') {
            $where[] = ['user_vip.company_vip_level', '=', $G['vip_level']];
        }
        return $where;
    }
    //    public function exportCompany1()
    //    {
    //        if (request()->isAjax()) {
    //            $G = request()->get();
    //            $where = $this->getSearchCompanyWhere();
    //            $Field = [
    //                'company.id,company.uid,company.title,company.stitle,company.logo,company.uscc,company.attestation,company.registered_capital,company.registered_capital_type,company.corporate_welfare,company.view,company.create_time',
    //                'nature.title as nature,finance.title as finance,size_type.title as size_type',
    //                'user_timer.online_time,user_timer.login_time',
    //                'industry.title as industry',
    //                'city.title as contacts_city,province.title as contacts_province,area.title as contacts_area',
    //                'content.contacts,content.contacts_mobile,content.contacts_wechat,content.contacts_tel,content.contacts_email,content.contacts_address,content.company_website,content.company_introduction,content.company_descript,content.template_id,content.contacts_lng,content.contacts_lat',
    //                'executives.executives,executives.executives_headimg,executives.executives_job_title,executives.executives_desc',
    //                'attestation.title as attestation',
    //                'app.app_name'
    //            ];
    //            $Data = CompanyModel::alias('company')->where($where)
    //                ->where(['nature.alias' => 'company/nature'])
    //                ->where(['finance.alias' => 'company/finance'])
    //                ->where(['size_type.alias' => 'company/size_type'])
    //                ->where(['attestation.alias' => 'company/attestation'])
    //                ->join('user user', 'user.id = company.uid')
    //                ->join('user_timer user_timer', 'user_timer.uid = company.uid', 'LEFT')
    //                ->join('company_industry industry', 'industry.id = company.industry_id', 'LEFT')
    //                ->join('company_content content', 'content.cid = company.id', 'LEFT')
    //                ->join('status_alias nature', 'nature.value=company.nature', 'LEFT')
    //                ->join('status_alias finance', 'finance.value=company.finance', 'LEFT')
    //                ->join('status_alias size_type', 'size_type.value=company.size_type', 'LEFT')
    //                ->join('status_alias attestation', 'attestation.value=company.attestation', 'LEFT')
    //                ->join('area province', 'province.id = content.contacts_area2', 'LEFT')
    //                ->join('area city', 'city.id = content.contacts_area1', 'LEFT')
    //                ->join('area area', 'area.id = content.contacts_area3', 'LEFT')
    //                ->join('company_executives executives', 'executives.cid = company.id', 'LEFT')
    //                ->join('api_app app', 'app.app_id = company.app_id', 'LEFT')
    //                ->field(implode(",", $Field))
    //                ->order('id desc')->paginate($G['pageSize'])->each(function ($v) {
    //                    $v['login_time'] = $v->login_time ? date('Y-m-d H:i:s', $v->login_time) : '';
    //                    $v['app_name'] = $v['app_name'] ? $v['app_name'] : '后台添加';
    //                    $v['jobs_count'] = JobsModel::where(['company_id' => $v->id])->count();
    //                    return $v;
    //                });
    //            if ($Data->items()) {
    //                $title = [
    //                    ['title' => 'ID', 'key' => 'id'],
    //                    ['title' => 'UID', 'key' => 'uid'],
    //                    ['title' => '企业名称', 'key' => 'title'],
    //                    ['title' => '企业简称', 'key' => 'stitle'],
    //                    ['title' => '统一社会信用代码', 'key' => 'uscc'],
    //                    ['title' => '企业性质', 'key' => 'nature'],
    //                    ['title' => '所属行业', 'key' => 'industry'],
    //                    ['title' => '所在地区', 'key' => 'area'],
    //                    ['title' => '企业规模', 'key' => 'size_type'],
    //                    ['title' => '注册资金', 'key' => 'registered_capital'],
    //                    ['title' => '注册来源', 'key' => 'app_name'],
    //                    ['title' => '发布职位数', 'key' => 'jobs_count'],
    //                    ['title' => '联系人', 'key' => 'contacts'],
    //                    ['title' => '联系电话', 'key' => 'contacts_mobile'],
    //                    ['title' => '固定电话', 'key' => 'contacts_tel'],
    //                    ['title' => '联系邮箱', 'key' => 'contacts_email'],
    //                    ['title' => '审核状态', 'key' => 'attestation'],
    //                    ['title' => '注册时间', 'key' => 'create_time'],
    //                    ['title' => '最后登录时间', 'key' => 'login_time']
    //                ];
    //                $spreadsheet = new Spreadsheet;
    //                $sheet = $spreadsheet->getActiveSheet();
    //
    //                //表头
    //                //设置单元格内容
    //                $titCol = 'A';
    //                foreach ($title as $key => $v) {
    //                    // 单元格内容写入
    //                    $sheet->setCellValue($titCol . '1', $v['title']);
    //                    $titCol++;
    //                }
    //                $row = 2;
    //                foreach ($Data->items() as $item) {
    //                    $dataCol = 'A';
    //                    foreach ($title as $key => $v) {
    //                        switch ($v['key']) {
    //                            case 'area':
    //                                $sheet->setCellValue($dataCol . $row, $item->contacts_province . $item->contacts_city . $item->contacts_area);
    //                                break;
    //                            case 'registered_capital':
    //                                $registered_capital = '万人民币';
    //                                if ($item->registered_capital_type)
    //                                    $registered_capital = '万美元';
    //                                $sheet->setCellValue('J' . $row, $item->registered_capital . $registered_capital);
    //                                break;
    //
    //                            default:
    //                                $sheet->setCellValue($dataCol . $row, $item[$v['key']]);
    //                                break;
    //                        }
    //                        $dataCol++;
    //                    }
    //                    $row++;
    //                }
    //                $filename = 'output/company/' . Session::get('AdminUser.uid') . '_' . date('YmdHis') . Str::random(4) . '.xlsx';
    //                if (!file_exists(dirname($filename)))
    //                    mkdir(dirname($filename), 0777, true);
    //                $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
    //                $writer->save($filename);
    //                return $this->ajaxReturn('生成~', 0, ['url' => '/' . $filename]);
    //            } else {
    //                return $this->ajaxReturn('暂无数据~', -100);
    //            }
    //        }
    //    }


    /**
     * 1、导出企业信息，导出用户选择的企业
     * 2、这个是改写方法，上面注释掉的exportCompany1为原方法
     * @author hhm
     * @since 20:35 2022-02-11
     **/
    public function exportCompany()
    {
        if (request()->isAjax()) {
            $G = request()->post();
            if (empty($G['selectNum']))
                return $this->ajaxReturn('请选择需要导出的企业', -100);
            //            $G = request()->get();
            $where = $this->getSearchCompanyWhere();
            $Field = [
                'company.id,company.uid,company.title,company.stitle,company.logo,company.uscc,company.attestation,company.registered_capital,company.registered_capital_type,company.corporate_welfare,company.view,company.create_time',
                'nature.title as nature,finance.title as finance,size_type.title as size_type',
                'user_timer.online_time,user_timer.login_time',
                'industry.title as industry',
                'city.title as contacts_city,province.title as contacts_province,area.title as contacts_area',
                'content.contacts,content.contacts_mobile,content.contacts_wechat,content.contacts_tel,content.contacts_email,content.contacts_address,content.company_website,content.company_introduction,content.company_descript,content.template_id,content.contacts_lng,content.contacts_lat',
                'executives.executives,executives.executives_headimg,executives.executives_job_title,executives.executives_desc',
                'attestation.title as attestation',
                'app.app_name'
            ];
            $Data = CompanyModel::alias('company')->where($where)
                ->where(['nature.alias' => 'company/nature'])
                ->where(['finance.alias' => 'company/finance'])
                ->where(['size_type.alias' => 'company/size_type'])
                ->where(['attestation.alias' => 'company/attestation'])
                ->join('user user', 'user.id = company.uid')
                ->join('user_timer user_timer', 'user_timer.uid = company.uid', 'LEFT')
                ->join('company_industry industry', 'industry.id = company.industry_id', 'LEFT')
                ->join('company_content content', 'content.cid = company.id', 'LEFT')
                ->join('status_alias nature', 'nature.value=company.nature', 'LEFT')
                ->join('status_alias finance', 'finance.value=company.finance', 'LEFT')
                ->join('status_alias size_type', 'size_type.value=company.size_type', 'LEFT')
                ->join('status_alias attestation', 'attestation.value=company.attestation', 'LEFT')
                ->join('area province', 'province.id = content.contacts_area2', 'LEFT')
                ->join('area city', 'city.id = content.contacts_area1', 'LEFT')
                ->join('area area', 'area.id = content.contacts_area3', 'LEFT')
                ->join('company_executives executives', 'executives.cid = company.id', 'LEFT')
                ->join('api_app app', 'app.app_id = company.app_id', 'LEFT')
                ->field(implode(",", $Field))
                ->whereIn('company.uid', $G['selectNum'])->select()->each(function ($v) {
                    $v['login_time'] = $v->login_time ? date('Y-m-d H:i:s', $v->login_time) : '';
                    $v['app_name'] = $v['app_name'] ? $v['app_name'] : '后台添加';
                    $v['jobs_count'] = JobsModel::where(['company_id' => $v->id])->count();
                    return $v;
                });
            if ($Data) {
                $title = [
                    ['title' => 'ID', 'key' => 'id'],
                    ['title' => 'UID', 'key' => 'uid'],
                    ['title' => '企业名称', 'key' => 'title'],
                    ['title' => '企业简称', 'key' => 'stitle'],
                    ['title' => '统一社会信用代码', 'key' => 'uscc'],
                    ['title' => '企业性质', 'key' => 'nature'],
                    ['title' => '所属行业', 'key' => 'industry'],
                    ['title' => '所在地区', 'key' => 'area'],
                    ['title' => '详细地址', 'key' => 'contacts_address'],
                    ['title' => '企业规模', 'key' => 'size_type'],
                    ['title' => '注册资金', 'key' => 'registered_capital'],
                    ['title' => '注册来源', 'key' => 'app_name'],
                    ['title' => '发布职位数', 'key' => 'jobs_count'],
                    ['title' => '联系人', 'key' => 'contacts'],
                    ['title' => '联系电话', 'key' => 'contacts_mobile'],
                    ['title' => '固定电话', 'key' => 'contacts_tel'],
                    ['title' => '联系邮箱', 'key' => 'contacts_email'],
                    ['title' => '审核状态', 'key' => 'attestation'],
                    ['title' => '注册时间', 'key' => 'create_time'],
                    ['title' => '最后登录时间', 'key' => 'login_time']
                ];
                $spreadsheet = new Spreadsheet;
                $sheet = $spreadsheet->getActiveSheet();

                //表头
                //设置单元格内容
                $titCol = 'A';
                foreach ($title as $key => $v) {
                    // 单元格内容写入
                    $sheet->setCellValue($titCol . '1', $v['title']);
                    $titCol++;
                }
                $row = 2;
                foreach ($Data as $item) {
                    $dataCol = 'A';
                    foreach ($title as $key => $v) {
                        switch ($v['key']) {
                            case 'area':
                                $sheet->setCellValue($dataCol . $row, $item->contacts_province . $item->contacts_city . $item->contacts_area);
                                break;
                            case 'registered_capital':
                                $registered_capital = '万人民币';
                                if ($item->registered_capital_type)
                                    $registered_capital = '万美元';
                                $sheet->setCellValue('J' . $row, $item->registered_capital . $registered_capital);
                                break;

                            default:
                                $sheet->setCellValue($dataCol . $row, $item[$v['key']]);
                                break;
                        }
                        $dataCol++;
                    }
                    $row++;
                }
                $filename = 'output/company/' . Session::get('AdminUser.uid') . '_' . date('YmdHis') . Str::random(4) . '.xlsx';
                if (!file_exists(dirname($filename)))
                    mkdir(dirname($filename), 0777, true);
                $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
                $writer->save($filename);
                return $this->ajaxReturn('生成~', 0, ['url' => '/' . $filename]);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        }
    }
    public function importCompany()
    {
        $VipController = VipController::getCate();
        View::assign('vip', $VipController);
        $arealist = Cache::get('arealist');
        View::assign('arealist', $arealist);
        $attestation = StatusAliasModel::getCate('company/attestation');
        View::assign('attestation', $attestation);
        $nature = StatusAliasModel::getCate('company/nature');
        View::assign('nature', $nature);
        $finance = StatusAliasModel::getCate('company/finance');
        View::assign('finance', $finance);
        $size_type = StatusAliasModel::getCate('company/size_type');
        View::assign('size_type', $size_type);
        $corporate_welfare = StatusAliasModel::getCate('company/corporate_welfare');
        View::assign('corporate_welfare', $corporate_welfare);
        $industry = CompanyIndustryModel::getCate();
        View::assign('industry', $industry);
        return View::fetch();
    }
    /**
     * 获取企业信息
     */
    public function getCompanyInfo($id)
    {
        $Find = CompanyModel::getCompanyInfoAll($id);
        if ($Find) {
            return $this->ajaxReturn('', 0, $Find);
        } else {
            return $this->ajaxReturn('无此企业数据', -100);
        }
    }
    public function setIsFamous($id, $status)
    {
        $CompanyModel = CompanyModel::find($id);
        $CompanyModel->is_famous = $status;
        if ($CompanyModel->save()) {
            return $this->ajaxReturn();
        } else {
            return $this->ajaxReturn('保存失败，请重试', -100);
        }
    }
    public function refreshCompany($id)
    {
        $CompanyModel = CompanyModel::where(['id' => $id])->find();
        $CompanyModel->refresh_time = time();
        if ($CompanyModel->save()) {
            return $this->ajaxReturn('已刷新', 0, ['refresh_time' => date('Y-m-d H:i', $CompanyModel->refresh_time)]);
        } else {
            return $this->ajaxReturn('刷新失败，请重试', -100);
        }
    }
    public function setCompanyDelete($id)
    {
        $CompanyModel = CompanyModel::find($id);
        if ($CompanyModel) {
            if ($CompanyModel->delete()) {
                return $this->ajaxReturn();
            } else {
                return $this->ajaxReturn('保存失败，请重试', -100);
            }
        } else {
            $CompanyModel = CompanyModel::onlyTrashed()->find($id);
            if ($CompanyModel) {
                if (empty(request()->get('force'))) {
                    if ($CompanyModel->restore()) {
                        return $this->ajaxReturn();
                    } else {
                        return $this->ajaxReturn('保存失败，请重试', -100);
                    }
                } else {
                    if ($CompanyModel->force()->delete()) {
                        return $this->ajaxReturn();
                    } else {
                        return $this->ajaxReturn('保存失败，请重试', -100);
                    }
                }
            }
        }
        return $this->ajaxReturn('企业不存在', -100);
    }
    /**
     * 添加企业
     */
    public function addCompany()
    {
        if (request()->isAjax()) {
            $D = request()->post();
            /**
             * 公司基本信息验证
             */
            try {
                validate(CompanyValidate::class)->check($D);
            } catch (ValidateException $e) {
                return $this->ajaxReturn($e->getError(), -100);
            }
            /**
             * 公司拓展信息验证
             */
            try {
                validate(CompanyContentValidate::class)->check($D);
            } catch (ValidateException $e) {
                return $this->ajaxReturn($e->getError(), -100);
            }
            /**
             * 用户
             */
            $UserModel = UserModel::where(['mobile' => $D['mobile']])->find();
            $UserInfoModel = null;
            $UserVipModel = null;
            $UserTimerModel = null;
            if ($UserModel) {
                if (CompanyModel::where(['uid' => $UserModel->id])->count())
                    return $this->ajaxReturn('该手机号已绑定企业主体', -100);
                $UserInfoModel = UserInfoModel::where(['uid' => $UserModel->id])->find();
                $UserVipModel = UserVipModel::where(['uid' => $UserModel->id])->find();
            } else {
                try {
                    validate(UserNameValidate::class)->check($D);
                } catch (ValidateException $e) {
                    return $this->ajaxReturn($e->getError(), -100);
                }
                $passHash = Str::random(4);
                $UserModel = new UserModel;
                $UserModel->mobile = $D['mobile'];
                if (!empty($D['email']))
                    $UserModel->email = $D['email'];
                $UserModel->password_hash = $passHash;
                if ($D['password']) {
                    $UserModel->password = UserModel::getPassword($passHash, $D['password']);
                } else {
                    $UserModel->password = UserModel::getPassword($passHash, $D['mobile']);
                }
                /**
                 * 用户信息
                 */
                $UserInfoModel = new UserInfoModel;
                $UserInfoModel->nickname = base64_encode(config('basic.nickname_header') . substr_replace($D['mobile'], '****', 3, 4));
                $UserInfoModel->headimg = config('xy_default_avatar.user');
                $UserInfoModel->role_type = 1;
                $UserTimerModel = new UserTimerModel;
                $UserTimerModel->online_time = time();
                $UserTimerModel->online_ip = request()->ip();
                $UserTimerModel->online_devices = substr(request()->header('user-agent'), 0, 200);
                $UserTimerModel->login_time = time();
                $UserTimerModel->login_ip = request()->ip();
                $UserTimerModel->login_devices = substr(request()->header('user-agent'), 0, 200);
                $UserTimerModel->register_time = time();
                $UserTimerModel->register_ip = request()->ip();
                $UserTimerModel->register_devices = substr(request()->header('user-agent'), 0, 200);
                $UserVipModel = new UserVipModel;
                $UserVipModel->update_vip = 0;
            }
            /**
             * 公司基本信息
             */
            $CompanyModel = new CompanyModel;
            $CompanyModel->title            =   $D['title'];
            $CompanyModel->stitle           =   $D['stitle'];
            $CompanyModel->business_license =   $D['business_license'];
            if (!empty($D['uscc']))
                $CompanyModel->uscc             =   $D['uscc'];
            $CompanyModel->logo             =   $D['logo'];
            $CompanyModel->attestation      =   $D['attestation'];
            $CompanyModel->nature           =   $D['nature'];
            $CompanyModel->industry_id      =   $D['industry_id'];
            $CompanyModel->region_id        =   $D['region_id'];
            $CompanyModel->size_type        =   $D['size_type'];
            $CompanyModel->registered_capital =   $D['registered_capital'];
            $CompanyModel->registered_capital_type =   $D['registered_capital_type'];
            if (!empty($D['corporate_welfare']))
                $CompanyModel->corporate_welfare =   implode(",", $D['corporate_welfare']);
            /**
             * 公司拓展信息
             */
            $CompanyContentModel = new CompanyContentModel;
            $CompanyContentModel->contacts             =   trimall($D['contacts']);
            $CompanyContentModel->contacts_mobile      =   $D['contacts_mobile'];
            $CompanyContentModel->contacts_tel         =   $D['contacts_tel'];
            $CompanyContentModel->contacts_email       =   $D['contacts_email'];
            $CompanyContentModel->contacts_area1       =   $D['contacts_area'][1];
            $CompanyContentModel->contacts_area2       =   $D['contacts_area'][0];
            $CompanyContentModel->contacts_area3       =   $D['contacts_area'][2];
            $CompanyContentModel->contacts_address     =   $D['contacts_address'];
            $CompanyContentModel->company_website      =   $D['company_website'];
            $CompanyContentModel->company_introduction =   $D['company_introduction'];
            $CompanyContentModel->company_descript     =   $D['company_descript'];
            $CompanyContentModel->template_id          =   $D['template_id'];
            $AdminUser = Session::get('AdminUser');
            $CrmCustomerModel = null;
            if (config('xy_crm.admin_role_id') && in_array($AdminUser['rid'], config('xy_crm.admin_role_id'))) {
                $CompanyModel->adviser_id = $AdminUser['uid'];
                $CrmCustomerModel = new CrmCustomerModel;
                $CrmCustomerModel->adviser_id = $AdminUser['uid'];
                $CrmCustomerModel->customer = $CompanyContentModel->contacts;
                $CrmCustomerModel->customer_mobile = $UserModel->mobile;
                $CrmCustomerModel->customer_email = $UserModel->email;
                $auto_cancel_adviser_time = config('xy_crm.auto_cancel_adviser_time');
                if (intval($auto_cancel_adviser_time)) {
                    $CrmCustomerModel->auto_cancel_adviser_time = time() + 3600 * 24 * intval($auto_cancel_adviser_time);
                }
            }

            $UserScoreModel = null;
            $VipModel = null;
            if (!empty($D['vip_level']) && $D['vip_level']) {
                $VipModel = VipModel::where(['level' => $D['vip_level'], 'is_company' => 1])->where('level', '>', 0)->find();
                if ($VipModel) {
                    $VipRuleModel = VipRuleModel::alias('rule')->where(['rule.vid' => $VipModel->id, 'rv.status' => 1, 'rv.type' => 'input'])
                        ->join('vip_rule_value rv', 'rv.id=rule.rid')
                        ->field('rule.vid,rule.rid,rule.value,rv.alias')->select()->toArray();
                    $UserVipModel->update_vip = 1;
                    $UserVipRuleList = [];
                    if ($VipRuleModel) {
                        list($expiry_time, $end) = Time::today();
                        $UserVipRuleModel = new UserVipRuleModel;
                        foreach ($VipRuleModel as $k => $v) {
                            $v['expiry_type'] = $VipModel->expiry_type;
                            $v['is_company'] = $VipModel->is_company;
                            switch ($v['alias']) {
                                case 'time-limit':
                                    $surplus_value = Time::daysToSecond($v['value']) + 3600 * 24;
                                    $expiry_time = $expiry_time + $surplus_value;
                                    if ($VipModel->is_company) {
                                        if ($UserVipModel->company_vip_time > time()) {
                                            $UserVipModel->company_vip_time = Db::raw('company_vip_time+' . $surplus_value);
                                        } else {
                                            $UserVipModel->company_vip_time = $expiry_time;
                                        }
                                    } else {
                                        if ($UserVipModel->personal_vip_time > time()) {
                                            $UserVipModel->personal_vip_time = Db::raw('personal_vip_time+' . $surplus_value);
                                        } else {
                                            $UserVipModel->personal_vip_time = $expiry_time;
                                        }
                                    }
                                    break;
                                case 'bonus-points':
                                    $UserInfoModel->score = Db::raw('score+' . $v['value']);
                                    $UserScoreModel = new UserScoreModel;
                                    $UserScoreModel->tid    =   0;
                                    $UserScoreModel->score  =   $v['value'];
                                    $UserScoreModel->desc   =   '开通' . $VipModel->title . '套餐赠送' . $v['value'] . '积分';
                                    break;
                                default:
                                    $v['level'] = $VipModel->level;
                                    $v['surplus_value'] = $v['value'];
                                    $UserVipRuleList[] = $v;
                                    break;
                            }
                        }
                    }
                }
            }

            // 启动事务
            Db::startTrans();
            try {
                if ($UserInfoModel) $UserModel->save();
                $CompanyModel->uid = $UserModel->id;
                $CompanyModel->save();
                $CompanyContentModel->cid = $CompanyModel->id;
                $CompanyContentModel->save();
                if (!empty($UserVipRuleList)) {
                    array_walk($UserVipRuleList, function (&$v, $k) use ($expiry_time, $UserModel) {
                        $v['uid'] = $UserModel->id;
                        $v['expiry_time'] = $expiry_time;
                        krsort($v);
                    });
                    $UserVipRuleModel->saveAll($UserVipRuleList);
                }
                if ($UserVipModel) {
                    $UserVipModel->uid = $UserModel->id;
                    $UserVipModel->save();
                }
                if ($UserInfoModel) {
                    $UserInfoModel->uid = $UserModel->id;
                    $UserInfoModel->save();
                }
                if ($UserTimerModel) {
                    $UserTimerModel->uid = $UserModel->id;
                    $UserTimerModel->save();
                }
                if ($UserScoreModel) {
                    $UserScoreModel->uid = $UserModel->id;
                    $UserScoreModel->save();
                }
                if ($CrmCustomerModel) {
                    $CrmCustomerModel->company_id = $CompanyModel->id;
                    $CrmCustomerModel->save();
                }
                // 提交事务
                Db::commit();
                Baidu::post(config('web.url') . '/company/' . $CompanyModel->id . '.html');
                return $this->ajaxReturn('保存成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试', -200);
            }
        } else {
            $VipController = VipController::getCate();
            View::assign('vip', $VipController);
            $arealist = Cache::get('arealist');
            View::assign('arealist', $arealist);
            $attestation = StatusAliasModel::getCate('company/attestation');
            View::assign('attestation', $attestation);
            $nature = StatusAliasModel::getCate('company/nature');
            View::assign('nature', $nature);
            $finance = StatusAliasModel::getCate('company/finance');
            View::assign('finance', $finance);
            $size_type = StatusAliasModel::getCate('company/size_type');
            View::assign('size_type', $size_type);
            $corporate_welfare = StatusAliasModel::getCate('company/corporate_welfare');
            View::assign('corporate_welfare', $corporate_welfare);
            $industry = CompanyIndustryModel::getCate();
            View::assign('industry', $industry);

            if (request()->isMobile())
                return View::fetch('add_company_mobile');
            return View::fetch();
        }
    }
    /**
     * 编辑企业
     */
    public function editCompany($id)
    {
        if (request()->isAjax()) {
            $D = request()->post();
            /**
             * 公司基本信息验证
             */
            try {
                validate(CompanyValidate::class)->check($D);
            } catch (ValidateException $e) {
                return $this->ajaxReturn($e->getError(), -100);
            }
            /**
             * 公司拓展信息验证
             */
            try {
                validate(CompanyContentValidate::class)->check($D);
            } catch (ValidateException $e) {
                return $this->ajaxReturn($e->getError(), -100);
            }
            /**
             * 公司基本信息
             */
            $CompanyModel = CompanyModel::find($id);
            $CompanyModel->title            =   $D['title'];
            $CompanyModel->stitle           =   $D['stitle'];
            $CompanyModel->business_license =   $D['business_license'];
            if ($D['uscc']) {
                $CompanyModel->uscc             =   $D['uscc'];
            } else {
                $CompanyModel->uscc             =   null;
            }
            $CompanyModel->logo             =   $D['logo'];
            $CompanyModel->attestation      =   $D['attestation'];
            $CompanyModel->nature           =   $D['nature'];
            $CompanyModel->industry_id      =   $D['industry_id'];
            $CompanyModel->region_id        =   $D['region_id'];
            $CompanyModel->size_type        =   $D['size_type'];
            $CompanyModel->registered_capital =   $D['registered_capital'];
            $CompanyModel->registered_capital_type =   $D['registered_capital_type'];
            if (!empty($D['corporate_welfare']))
                $CompanyModel->corporate_welfare =   empty($D['corporate_welfare']) ? '' : implode(",", $D['corporate_welfare']);
            /**
             * 公司拓展信息
             */
            $CompanyContentModel = CompanyContentModel::where(['cid' => $CompanyModel->id])->find();
            $CompanyContentModel->contacts             =   trimall($D['contacts']);
            $CompanyContentModel->contacts_mobile      =   $D['contacts_mobile'];
            $CompanyContentModel->contacts_tel         =   $D['contacts_tel'];
            $CompanyContentModel->contacts_email       =   $D['contacts_email'];
            $CompanyContentModel->contacts_area1       =   $D['contacts_area'][1];
            $CompanyContentModel->contacts_area2       =   $D['contacts_area'][0];
            $CompanyContentModel->contacts_area3       =   $D['contacts_area'][2];
            $CompanyContentModel->contacts_address     =   $D['contacts_address'];
            $CompanyContentModel->company_website      =   $D['company_website'];
            $CompanyContentModel->company_introduction =   $D['company_introduction'];
            $CompanyContentModel->company_descript     =   $D['company_descript'];
            $CompanyContentModel->template_id          =   $D['template_id'];
            $UserInfoModel = null;
            $UserScoreModel = null;
            $VipModel = null;
            $UserVipModel = UserVipModel::where(['uid' => $CompanyModel->uid])->find();
            if (!empty($D['vip_level']) && (int) $D['vip_level'] !== $UserVipModel->company_vip_level) {
                $VipModel = VipModel::where(['level' => $D['vip_level'], 'is_company' => 1])->where('level', '>', 0)->find();
                if ($VipModel) {
                    $VipRuleModel = VipRuleModel::alias('rule')->where(['rule.vid' => $VipModel->id, 'rv.status' => 1, 'rv.type' => 'input'])
                        ->join('vip_rule_value rv', 'rv.id=rule.rid')
                        ->field('rule.vid,rule.rid,rule.value,rv.alias')->select()->toArray();
                    $UserInfoModel = UserInfoModel::where(['uid' => $CompanyModel->uid])->find();
                    if (!$UserVipModel) {
                        $UserVipModel = new UserVipModel;
                        $UserVipModel->uid = $CompanyModel->uid;
                    }
                    $UserVipModel->update_vip = 1;
                    $UserVipRuleList = [];
                    if ($VipRuleModel) {
                        list($expiry_time, $end) = Time::today();
                        $UserVipRuleModel = new UserVipRuleModel;
                        foreach ($VipRuleModel as $k => $v) {
                            $v['expiry_type'] = $VipModel->expiry_type;
                            $v['is_company'] = $VipModel->is_company;
                            switch ($v['alias']) {
                                case 'time-limit':
                                    $surplus_value = Time::daysToSecond($v['value']) + 3600 * 24;
                                    $expiry_time = $expiry_time + $surplus_value;
                                    if ($VipModel->is_company) {
                                        if ($UserVipModel->company_vip_time > time()) {
                                            $UserVipModel->company_vip_time = Db::raw('company_vip_time+' . $surplus_value);
                                        } else {
                                            $UserVipModel->company_vip_time = $expiry_time;
                                        }
                                    } else {
                                        if ($UserVipModel->personal_vip_time > time()) {
                                            $UserVipModel->personal_vip_time = Db::raw('personal_vip_time+' . $surplus_value);
                                        } else {
                                            $UserVipModel->personal_vip_time = $expiry_time;
                                        }
                                    }
                                    break;
                                case 'bonus-points':
                                    $UserInfoModel->score = Db::raw('score+' . $v['value']);
                                    $UserScoreModel = new UserScoreModel;
                                    $UserScoreModel->tid    =   0;
                                    $UserScoreModel->score  =   $v['value'];
                                    $UserScoreModel->desc   =   '开通' . $VipModel->title . '套餐赠送' . $v['value'] . '积分';
                                    break;
                                default:
                                    $v['uid'] = $CompanyModel->uid;
                                    $v['level'] = $VipModel->level;
                                    $v['surplus_value'] = $v['value'];
                                    $UserVipRuleList[] = $v;
                                    break;
                            }
                        }
                    }
                    if (!empty($UserVipRuleList)) {
                        array_walk($UserVipRuleList, function (&$v, $k) use ($expiry_time) {
                            $v['expiry_time'] = $expiry_time;
                            krsort($v);
                        });
                    }
                } else {
                    $UserVipModel = null;
                }
            }

            // 启动事务
            Db::startTrans();
            try {
                $CompanyModel->save();
                $CompanyContentModel->save();
                if (!empty($UserVipRuleList)) $UserVipRuleModel->saveAll($UserVipRuleList);
                if ($UserInfoModel) $UserInfoModel->save();
                if ($UserVipModel) $UserVipModel->save();
                if ($UserScoreModel) $UserScoreModel->save();
                // 提交事务
                Db::commit();
                return $this->ajaxReturn('保存成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试', -200);
            }
        } else {
            $VipController = VipController::getCate();
            View::assign('vip', $VipController);
            $Find = CompanyModel::getEditFind($id);
            View::assign('Find', $Find);
            $arealist = Cache::get('arealist');
            View::assign('arealist', $arealist);
            $attestation = StatusAliasModel::getCate('company/attestation');
            View::assign('attestation', $attestation);
            $nature = StatusAliasModel::getCate('company/nature');
            View::assign('nature', $nature);
            $finance = StatusAliasModel::getCate('company/finance');
            View::assign('finance', $finance);
            $size_type = StatusAliasModel::getCate('company/size_type');
            View::assign('size_type', $size_type);
            $corporate_welfare = StatusAliasModel::getCate('company/corporate_welfare');
            View::assign('corporate_welfare', $corporate_welfare);
            $industry = CompanyIndustryModel::getCate();
            View::assign('industry', $industry);

            if (request()->isMobile())
                return View::fetch('add_company_mobile');
            return View::fetch('add_company');
        }
    }
    public function giveCompanyVip()
    {
        $D = request()->post();
        $UserVipModel = UserVipModel::where(['uid' => $D['uid']])->find();
        if (!$UserVipModel) $this->ajaxReturn('用户不存在', -200);
        $UserVipRuleList = [];
        $VipModel = null;
        $UserInfoModel = null;
        $UserScoreModel = null;
        list($expiry_time, $end) = Time::today();
        if (empty($D['id'])) {
            if (!empty($D['time'])) {
                $viptime = strtotime($D['time'] . ' 23:59:59');
                if ($viptime < time()) {
                    $UserVipModel->company_vip_time = time() + 5;
                    $viptime = null;
                } else {
                    $UserVipModel->company_vip_time = $viptime;
                }
            } else {
                $surplus_value = Time::daysToSecond($D['day']);
                $expiry_time = $expiry_time + $surplus_value;
                if ($UserVipModel->company_vip_time > time()) {
                    $viptime = $UserVipModel->company_vip_time + $surplus_value;
                    $UserVipModel->company_vip_time = Db::raw('company_vip_time+' . $surplus_value);
                } else {
                    $UserVipModel->company_vip_time = $expiry_time;
                    $viptime = $expiry_time;
                }
            }
        } else {
            $additional_day = 0;
            if (!empty($D['day']))
                $additional_day = Time::daysToSecond($D['day']);
            $VipModel = VipModel::where(['id' => $D['id']])->find();
            $viptime = time();
            if ($VipModel) {
                $VipRuleModel = VipRuleModel::alias('rule')->where(['rule.vid' => $VipModel->id, 'rv.status' => 1, 'rv.type' => 'input'])
                    ->join('vip_rule_value rv', 'rv.id=rule.rid')
                    ->field('rule.vid,rule.rid,rule.value,rv.alias')->select()->toArray();
                foreach ($VipRuleModel as $k => $v) {
                    foreach ($D['vipRuleValueSelect'] as $vo) {
                        if ($v['alias'] == $vo['alias']) {
                            $VipRuleModel[$k]['value'] = $vo['value'];
                        }
                    }
                }
                $UserInfoModel = UserInfoModel::where(['uid' => $UserVipModel->uid])->find();
                $UserVipModel->update_vip = 1;
                if ($VipRuleModel) {
                    $UserVipRuleModel = new UserVipRuleModel;
                    foreach ($VipRuleModel as $k => $v) {
                        $v['expiry_type'] = $VipModel->expiry_type;
                        $v['is_company'] = $VipModel->is_company;
                        switch ($v['alias']) {
                            case 'time-limit':
                                if (!empty($D['time'])) {
                                    $viptime = strtotime($D['time'] . ' 23:59:59');
                                    $expiry_time = $viptime;
                                    if ($VipModel->level)
                                        $UserVipModel->company_vip_time = $viptime;
                                } else {
                                    $surplus_value = 0;
                                    if ($v['value']) {
                                        $surplus_value = Time::daysToSecond($v['value']) + 3600 * 24 + $additional_day;
                                    } else {
                                        $expiry_time = time() + 3600 * 24 * 365 * 10;
                                        $viptime = null;
                                    }
                                    $expiry_time = $expiry_time + $surplus_value + $additional_day;
                                    if ($VipModel->level) {
                                        if ($VipModel->is_company) {
                                            if ($UserVipModel->company_vip_time > time()) {
                                                $viptime = $UserVipModel->company_vip_time + $surplus_value;
                                                $UserVipModel->company_vip_time = Db::raw('company_vip_time+' . $surplus_value);
                                            } else {
                                                $UserVipModel->company_vip_time = $expiry_time;
                                                $viptime = $expiry_time;
                                            }
                                        } else {
                                            if ($UserVipModel->personal_vip_time > time()) {
                                                $UserVipModel->personal_vip_time = Db::raw('personal_vip_time+' . $surplus_value);
                                            } else {
                                                $UserVipModel->personal_vip_time = $expiry_time;
                                            }
                                        }
                                    }
                                }
                                break;
                            case 'bonus-points':
                                $UserInfoModel->score = Db::raw('score+' . $v['value']);
                                $UserScoreModel = new UserScoreModel;
                                $UserScoreModel->tid    =   0;
                                $UserScoreModel->score  =   $v['value'];
                                $UserScoreModel->desc   =   '开通' . $VipModel->title . '套餐赠送' . $v['value'] . '积分';
                                break;
                            default:
                                $v['uid'] = $UserVipModel->uid;
                                $v['level'] = $VipModel->level;
                                $v['surplus_value'] = $v['value'];
                                $UserVipRuleList[] = $v;
                                break;
                        }
                    }
                }
                if (!empty($UserVipRuleList)) {
                    array_walk($UserVipRuleList, function (&$v, $k) use ($expiry_time) {
                        $v['expiry_time'] = $expiry_time;
                        krsort($v);
                    });
                }
            } else {
                return $this->ajaxReturn('套餐不存在', -200);
            }
        }
        // 启动事务
        Db::startTrans();
        try {
            // dd($UserVipRuleModel, $UserInfoModel, $UserVipModel, $UserScoreModel);
            if (!empty($UserVipRuleList)) $UserVipRuleModel->saveAll($UserVipRuleList);
            if ($UserInfoModel) $UserInfoModel->save();
            if ($UserVipModel) $UserVipModel->save();
            if ($UserScoreModel) $UserScoreModel->save();
            // 提交事务
            Db::commit();
            return $this->ajaxReturn('保存成功', 0, [
                'vip_title' => $VipModel ? $VipModel->title : '',
                'company_vip_time' => $viptime ? date('Y-m-d', $viptime) : ''
            ]);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->ajaxReturn('保存失败，请重试', -200, ['msg' => $e->getMessage(), 'line' => $e->getLine()]);
        }
    }
    public function setAdviser($id, $adviser_id)
    {
        $crm_distribution_pattern = config('xy_crm.crm_distribution_pattern');
        if ($crm_distribution_pattern === NULL) {
            $CompanyModel = CompanyModel::where(['id' => $id])->find();
            $CompanyModel->adviser_id = $adviser_id;
            if ($CompanyModel->save()) {
                return $this->ajaxReturn('已设置');
            } else {
                return $this->ajaxReturn('设置失败，请重试', -100);
            }
        } else {
            $McaWhere['domain'] = 'bsadmin';
            $McaWhere['controller'] = 'Crm';
            $McaWhere['fun'] = 'setAdviser';
            $roleId = Session::get('AdminUser.rid');
            $role = config('role.' . $roleId);
            $McaFind = config('auth.' . $McaWhere['domain'] . '/' . $McaWhere['controller'] . '/' . $McaWhere['fun']);
            if ($McaFind && in_array($McaFind['aid'], $role['auth'])) {
                if ($McaFind['status']) {
                    if (!class_exists('app\bsadmin\controller\Crm'))
                        return $this->ajaxReturn('CRM模块不存在', -100);
                    $CrmController = new \app\bsadmin\controller\Crm;
                    return $CrmController->setAdviser($id, $adviser_id);
                } else {
                    return $this->ajaxReturn('系统维护，暂停访问', -100);
                }
            } else {
                return $this->ajaxReturn('无权访问', -100);
            }
        }
    }

    public function demeanor()
    {
        if (request()->isAjax()) {
            $G = request()->get();
            $where = [];
            if ($G['key']) {
                switch ($G['search_type']) {
                    case 'company_id':
                        $where[] = ['d.cid', '=', $G['key']];
                        break;
                    case 'company_name':
                        $where[] = ['company.title', 'like', '%' . $G['key'] . '%'];
                        break;
                }
            }
            if ($G['status'] != 'all') {
                $where[] = ['d.status', '=', $G['status']];
            }
            $Data = CompanyDemeanorModel::alias('d')->where($where)
                ->join('company company', 'company.id = d.cid')
                ->field('d.*,company.title')
                ->order('id desc')->paginate($G['pageSize'])->each(function ($v) {
                    $v['url'] = config('web.imgurl') . $v['path'];
                    return $v;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('', 0, $Data);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        } else {
            if (request()->isMobile())
                return View::fetch('demeanor_mobile');
            return View::fetch();
        }
    }

    public function logo()
    {
        if (!request()->isAjax()) {
            if (request()->isMobile())
                return View::fetch('logo_mobile');
            return View::fetch();
        }
        $page = input('page', 1);
        $limit = input('pageSize', 10);
        $type = input('search_type', null);
        $key = input('key', null);
        $status = (!empty(input('status')) || is_numeric(input('status'))) ? input('status') : [0, 1, 2];
        $where = [];
        if ($type == 'company_name') {
            // 若key不为空，则按照传入的key筛选企业名符合的数据，反之查询所有
            $where[] = empty($key) ? true : ['company.title', 'LIKE', $key . '%'];
        } else {
            // 若key不为空，则按照传入的key筛选企业id符合的数据，反之查询所有
            $where[] = empty($key) ? true : ['company.id' => $key];
        }
        $where[] = ['status', 'IN', $status];
        $data = CompanyLogoExamineModel::alias('examine')
            ->join('company company', 'company.id=examine.company_id')
            ->where($where)
            ->field([
                'examine.*',
                'company.title' => 'company_name',
            ])
            ->page($page, $limit)
            ->select();
        $total = CompanyLogoExamineModel::alias('examine')
            ->join('company company', 'company.id=examine.company_id')
            ->where($where)
            ->count();
        $result = [
            'data' => $data,
            'total' => $total
        ];
        return $this->ajaxReturn('success', 0, $result);
    }

    public function setCompanyDemeanor($id, $status)
    {
        $CompanyDemeanorModel = CompanyDemeanorModel::where(['id' => $id])->find();
        $CompanyDemeanorModel->status = $status;
        if ($CompanyDemeanorModel->save()) {
            return $this->ajaxReturn('已保存', 0, ['update_time' => date('Y-m-d H:i:s')]);
        } else {
            return $this->ajaxReturn('保存失败，请重试', -100);
        }
    }

    public function setCompanyLogo($id, $status)
    {
        $reason = input('post.reason', '');
        $logo = CompanyLogoExamineModel::where('id', $id)->find();
        if (!$logo) {
            return $this->ajaxReturn('错误的参数！', -100);
        }
        // 审核通过
        if ($status == 1) {
            CompanyModel::where('id', $logo->company_id)->update(['logo' => $logo->after_logo]);
            $logo->save(['status' => 1]);
        } else {
            $logo->save(['status' => 2, 'reject_reason' => $reason]);
        }
        $msg = $status == 1 ? '已通过' : '已驳回';
        return $this->ajaxReturn($msg, 0);
    }

    public function companyAttestation()
    {
        if (request()->isAjax()) {
            $G = request()->get();
            $where = [];
            if ($G['key']) {
                switch ($G['search_type']) {
                    case 'id':
                        $where[] = ['a.cid', '=', $G['key']];
                        break;
                    case 'uscc':
                        $where[] = ['a.uscc', '=', $G['key']];
                        break;
                    case 'company_name':
                        $where[] = ['company.title', 'like', '%' . $G['key'] . '%'];
                        break;
                }
            }
            if ($G['status'] != 'all') {
                $where[] = ['a.status', '=', $G['status']];
            }
            $Data = CompanyAttestationModel::alias('a')->where($where)
                ->join('company company', 'company.id = a.cid')
                ->field('a.*,company.title')
                ->order('id desc')->paginate($G['pageSize'])->each(function ($v) {
                    $v['url'] = config('web.imgurl') . $v['business_license'];
                    return $v;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('', 0, $Data);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        } else {
            if (request()->isMobile())
                return View::fetch('company_attestation_mobile');
            return View::fetch();
        }
    }
    public function setCompanyAttestationStatus($id, $status, $msg = '')
    {
        $CompanyAttestationModel = CompanyAttestationModel::where(['id' => $id])->find();
        $CompanyModel = CompanyModel::where(['id' => $CompanyAttestationModel->cid])->find();
        if ($status == 1) {
            $CompanyAttestationModel->status = 1;
            $CompanyModel->attestation = 3;
            $CompanyModel->uscc = $CompanyAttestationModel->uscc;
            $CompanyModel->business_license = $CompanyAttestationModel->business_license;
            if (CompanyModel::where(['uscc' => $CompanyAttestationModel->uscc])->count())
                return $this->ajaxReturn('此统一社会信用代码已实名', -100);
            // 启动事务
            Db::startTrans();
            try {
                $CompanyAttestationModel->save();
                $CompanyModel->save();
                // 提交事务
                Db::commit();
                return $this->ajaxReturn('已保存');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试', -100);
            }
        } else {
            $CompanyAttestationModel->status = 2;
            $CompanyAttestationModel->msg = $msg;
            $CompanyModel->attestation = 2;
            // 启动事务
            Db::startTrans();
            try {
                $CompanyAttestationModel->save();
                $CompanyModel->save();
                // 提交事务
                Db::commit();
                return $this->ajaxReturn('已保存');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试', -100);
            }
        }
    }
    public function setting()
    {
        $Data = ConfigModel::getList([['ctype', 'in', ['xy_company', 'xy_default_avatar', 'xy_resume']]]);
        View::assign('Data', $Data);
        View::assign('ctype', 'xy_company');
        return View::fetch('setting/company');
    }
    public function industry()
    {
        if (request()->isAjax()) {
            $G = request()->get();
            if (empty($G['cid'])) {
                return $this->ajaxReturn('', 0, CompanyIndustryModel::getSelect(['pid' => 0]));
            } else {
                return $this->ajaxReturn('', 0, CompanyIndustryModel::getSelect(['pid' => $G['cid']]));
            }
        } else {
            return View::fetch();
        }
    }
    /**
     * 编辑文章分类
     */
    public function editIndustry($id)
    {
        if (request()->isPost()) {
            $D = request()->post();
            $rule =   [
                'title'     => 'require|max:50',
            ];
            $msg  =   [
                'title.require' => 'Title 不能为空',
                'title.max'     => 'Title 不能超过50个字符',
            ];
            $Validate = Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if (!$result) {
                return $this->ajaxReturn($Validate->getError(), -100);
            }
            $CompanyIndustryModel = CompanyIndustryModel::find($id);
            $CompanyIndustryModel->title    = $D['title'];
            $CompanyIndustryModel->status    = $D['status'];
            $CompanyIndustryModel->pid    = $D['pid'];
            if (!empty($D['sort']))
                $CompanyIndustryModel->sort    = $D['sort'];
            if ($CompanyIndustryModel->save()) {
                $this->setCacheIndustry();
                return $this->ajaxReturn('保存成功');
            } else {
                return $this->ajaxReturn('保存失败，请重试', -200);
            }
        } else {
            $Find = CompanyIndustryModel::where(['id' => $id])->find();
            View::assign('Find', $Find);
            $industry = CompanyIndustryModel::getSelect(['pid' => 0]);
            View::assign('industry', $industry);
            return View::fetch('add_industry');
        }
    }
    /**
     * 添加文章分类
     */
    public function addIndustry()
    {
        if (request()->isPost()) {
            $D = request()->post();
            $rule =   [
                'title'     => 'require|max:50',
            ];
            $msg  =   [
                'title.require' => 'Title 不能为空',
                'title.max'     => 'Title 不能超过50个字符',
            ];
            $Validate = Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if (!$result) {
                return $this->ajaxReturn($Validate->getError(), -100);
            }
            $CompanyIndustryModel = new CompanyIndustryModel;
            $CompanyIndustryModel->title    = $D['title'];
            $CompanyIndustryModel->status    = $D['status'];
            if (!empty($D['sort']))
                $CompanyIndustryModel->sort    = $D['sort'];
            if ($CompanyIndustryModel->save()) {
                $this->setCacheIndustry();
                return $this->ajaxReturn('保存成功');
            } else {
                return $this->ajaxReturn('保存失败，请重试', -200);
            }
        } else {
            $industry = CompanyIndustryModel::getSelect(['pid' => 0]);
            View::assign('industry', $industry);
            return View::fetch();
        }
    }
    public function setCompanyIndustryStatus($id, $status)
    {
        $CompanyIndustryModel = CompanyIndustryModel::find($id);
        $CompanyIndustryModel->status = $status;
        if ($CompanyIndustryModel->save()) {
            return $this->ajaxReturn();
        } else {
            return $this->ajaxReturn('保存失败，请重试', -100);
        }
    }
    public function setCacheIndustry()
    {
        $Data = CompanyIndustryModel::getCache();
        Cache::set('CompanyIndustry', $Data);
        return $this->ajaxReturn('保存成功');
    }
}
